//
//  MainMessagesController.m
//  消息中心主页
//
//
//
//

#import "MainMessagesController.h"
#import "MainMessageCell.h"
#import "XXCell.h"
#import "PagingMessageController.h"
#import "HDH5ViewController.h"
#import "LYMessageList.h"
#import "LYPagingMessageModel.h"

@interface MainMessagesController ()
//@property (weak, nonatomic) IBOutlet UISegmentedControl *control;
//记录是活动还是消息
@property (unsafe_unretained, nonatomic) NSInteger index;

@property (nonatomic, strong) ShowNoNetworkView* workView;

//用一个数来记录用户上拉加载的次数
@property (nonatomic, unsafe_unretained) NSInteger slCount;
@property (nonatomic, strong) MJRefreshAutoGifFooter *footer;
@property (nonatomic, strong) MJRefreshGifHeader *header;

@end

@implementation MainMessagesController

- (NSMutableArray*)messages
{
    if (!_messages)
    {
        _messages = [NSMutableArray array];
    }
    return _messages;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.index = 0;
    self.slCount = 1;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:LoadImage(@"back1") style:UIBarButtonItemStylePlain target:self action:@selector(popRootVC)];
    [self.tableView registerNib:[UINib nibWithNibName:@"MainMessageCell" bundle:nil] forCellReuseIdentifier:@"HDCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"XXCell" bundle:nil] forCellReuseIdentifier:@"XXCell"];
    
    self.header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.header.lastUpdatedTimeLabel.hidden = YES;
    self.tableView.header = self.header;
    self.footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.footer = self.footer;
    [self.footer setHidden:YES];
    
    //请求数据
    [self postMessageListWithPageSize:self.slCount withPages:10];
}

#pragma mark  //获取通知列表数据
- (void)postMessageListWithPageSize:(NSInteger)size withPages:(NSInteger)page
{
    //    //设置缓存的key
    //    NSString* cacheStr = [NSString stringWithFormat:@"getMessagesList"];
    NSDictionary* json = @{@"page":[NSString stringWithFormat:@"%ld",(long)size],
                           @"rows":[NSString stringWithFormat:@"%ld",(long)page],
                           };
    NSLog(@"json = %@",json);
    //字符串转字符串
    NSString* str = [JSONToString dictionaryToJson:json];
    //转md5
    MyAdditions* md5 = [[MyAdditions alloc]init];
    md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
    NSString* md5_Str = [md5 md5];
    NSString* url = [NSString stringWithFormat:@"%@sign=%@",MessageURL,md5_Str];
    [self getMessageListWithURL:url withParam:json];
}

- (void)getMessageListWithURL:(NSString*)url withParam:(NSDictionary*)param
{
    HKTShowNetworkView* networking = [HKTShowNetworkView shareInstanceWithTitle:@"检测到您的设备没有连接网络!" withImageStr:@"no_record" withType:0 withFrame:CGRectMake(0, 0, UISCREENWEITH, self.tableView.frame.size.height) withVC:self];
    [networking showNetworkViewWithSuccess:^{
        
        self.tableView.scrollEnabled = YES;
        [self.header setHidden:NO];
        
        [XHNetworking POST:url parameters:param  success:^(NSData *responseObject) {
            //网络读取数据
            [self readMessageListWithData:responseObject];
        } failure:^(NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.footer setHidden:YES];
                [self endRefresh];
                if (self.messages.count == 0)
                {
                    [self createWorkView];
                }
                else
                {
                    [self removeWorkView];
                }
                [self.tableView reloadData];
            });
        }];
        
    } failure:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            self.tableView.scrollEnabled = NO;
            [self.footer setHidden:YES];
            [self.header setHidden:YES];
            [self endRefresh];
        });
    } click:^(NSInteger type) {
        NSLog(@"点击了什么类型的按钮%ld!",(long)type);
        if (type == 0)
        {
            //弹出网络提示
            
        }
    }];
}

- (void)readMessageListWithData:(NSData*)data
{
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSString* str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@" 获取通知列表数据str = %@",str);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if ([json isKindOfClass:[NSDictionary class]] && json)
        {
            if ([json[@"resultCode"] isEqualToString:@"0"])
            {
                if ([json[@"responseObject"] isKindOfClass:[NSDictionary class]])
                {
                    if ([json[@"responseObject"][@"rows"] isKindOfClass:[NSArray class]])
                    {
                        for (NSDictionary* dic in json[@"responseObject"][@"rows"])
                        {
                            LYMessageList* list = [LYMessageList messageListWithJSON:dic];
                            [self.messages addObject:list];
                        }
                        //多少页
                        NSInteger i = [json[@"responseObject"][@"pages"] integerValue];
                        //当前页
                        NSInteger i1 = [json[@"responseObject"][@"pageNum"] integerValue];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self.footer setHidden:NO];
                            //当刚好数据为10条、总页数只有一页时
                            if (i == i1)
                            {
                                [self.tableView.footer noticeNoMoreData];
                            }
                            if ([json[@"responseObject"][@"rows"] count] == 0)
                            {
                                [self.tableView.footer noticeNoMoreData];
                            }
                        });
                    }
                    else
                    {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self.footer setHidden:YES];
                            
                        });
                    }
                }
                else
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.footer setHidden:YES];
                        
                    });
                }
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.footer setHidden:YES];
                    
                });
            }
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.footer setHidden:YES];
                
            });
        }
        //通知主线程刷新
        dispatch_async(dispatch_get_main_queue(), ^{
            [self endRefresh];
            if (self.messages.count == 0)
            {
                [self createWorkView];
            }
            else
            {
                [self removeWorkView];
            }
            [self.tableView reloadData];
        });
    });
}

/**
 *  停止刷新
 */
-(void)endRefresh
{
    if ([self.tableView.header isRefreshing])
    {
        [self.tableView.header endRefreshing];
    }
    if ([self.tableView.footer isRefreshing])
    {
        [self.tableView.footer endRefreshing];
    }
}


//下拉刷新
- (void)loadNewData
{
    NSLog(@"下拉刷新");
    self.slCount = 1;
    [self.messages removeAllObjects];
    [self.tableView.header beginRefreshing];
    [self.tableView.footer resetNoMoreData];
    [self removeWorkView];
    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC));
    dispatch_after(delay, dispatch_get_main_queue(), ^{
        //请求数据
        [self postMessageListWithPageSize:self.slCount withPages:10];
    });
}

//上拉加载
- (void)loadMoreData
{
    self.slCount++;
    //self.myDistance = self.tableView.contentOffset.y;
    NSLog(@"self.slCount = %ld",(long)self.slCount);
//    [self.tableView.footer resetNoMoreData];
    NSLog(@"上拉加载");
    [self removeWorkView];
    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC));
    dispatch_after(delay, dispatch_get_main_queue(), ^{
        //请求数据
        [self postMessageListWithPageSize:self.slCount withPages:10];
    });
}

- (void)popRootVC
{
    [self.navigationController popViewControllerAnimated:YES];
}

//点击切换活动、消息,更新表格
//- (IBAction)changeType:(UISegmentedControl *)sender
//{
//    self.index = sender.selectedSegmentIndex;
//    [self.tableView reloadData];
////    switch (sender.selectedSegmentIndex)
////    {
////        case 0:
////
////            break;
////        case 1:
////
////            break;
////        default:
////            return;
////            break;
////    }
//}

- (void)createWorkView
{
    if (self.workView == nil)
    {
        self.workView = [[ShowNoNetworkView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        self.workView.labelText = @"没有活动消息";
        self.workView.imageName = @"no_record";
        self.workView.myType = MyTypeOfViewForShowError;
        [self.workView createAllSubView];
        __weak MainMessagesController* mySelf = self;
        [self.workView addActionWithBlock:^{
            //请求数据
            [mySelf postMessageListWithPageSize:mySelf.slCount withPages:10];
        }];
        [self.tableView addSubview:self.workView];
        
    }
}

- (void)removeWorkView
{
    self.workView.frame = CGRectZero;
    [self.workView removeFromSuperview];
    self.workView = nil;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.index == 0)
    {
        return self.messages.count;
    }
    else
    {
        return 10;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.index == 0)
    {
        UITableViewCell* cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
        return cell.bounds.size.height;
    }
    else
    {
        return 70;
    }
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.index == 0)
    {
        MainMessageCell* cell = (MainMessageCell*)[tableView dequeueReusableCellWithIdentifier:@"HDCell"];
        if (cell == nil)
        {
            //直接加载 xib
            cell = [[[NSBundle mainBundle]loadNibNamed:@"MainMessageCell" owner:self options:nil] lastObject];
        }
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        LYMessageList* list = self.messages[indexPath.row];
        LYPagingMessageModel* mode = [LYPagingMessageModel mode];
        mode.title = list.title;
        mode.detail = list.content;
        mode.date = list.createDate;
        mode.imageURL = list.cover;
        [cell setModel:mode];
        [cell setNeedsLayout];
        
        return cell;
    }
    else
    {
        XXCell* cell = (XXCell*)[tableView dequeueReusableCellWithIdentifier:@"XXCell" forIndexPath:indexPath];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        //园切角
        cell.backView.layer.cornerRadius = 8.0;
        cell.backView.layer.masksToBounds = YES;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.index == 0)
    {
        LYMessageList* list = self.messages[indexPath.row];
        //推出活动页面详情
        HDH5ViewController* vc = [[HDH5ViewController alloc]initWithNibName:@"HDH5ViewController" bundle:nil];
        vc.html = [NSString stringWithFormat:@"%@?id=%@&customerId=%@",MessageURL1,list.myId,[TRUserAgenCode getCustomerId]];
        NSLog(@"消息页面链接:%@",vc.html);
        vc.small_picture = @"fre_get1.png";
        vc.product_features = list.content;
        vc.myTitle = list.title;
        vc.small_picture = list.pic;
        [self.navigationController pushViewController:vc animated:YES];
    }
    else
    {
        //推出消息列表页面
        PagingMessageController* pagingVC = [[PagingMessageController alloc]initWithNibName:@"PagingMessageController" bundle:nil];
        pagingVC.title = @"系统消息";
        [self.navigationController pushViewController:pagingVC animated:YES];
    }
}

@end
